//
//  MJTUserAccount.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/10.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit

class MJTUserAccount: NSObject,NSCoding {

    // 过期时间
    var expiresDate: NSDate?
    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    var uid: Int64 = 0

    var name: String?
    //  用户头像
    var avatar_large: String?
    init(dic: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    //重写字段防止崩溃
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {

    }
   override var description: String {

        let keys = ["access_token","expires_in","uid", "name", "avatar_large"]
        return dictionaryWithValuesForKeys(keys).description

    }
    //MARK: -归档与解档
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")

    }
    //解档 需要遵守NSCodeing协议
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    //保存用户对象
    func saveUserAccount()->Bool {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
        print(path)

        let result = NSKeyedArchiver.archiveRootObject(self, toFile: path)
        return result
    }
    // 通过路径读取用户对象
    class func loadUserAccount()-> MJTUserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? MJTUserAccount

    }
}
